package example.json.msg.controller;

import example.json.msg.vo.Result;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.dom4j.*;
import static example.json.msg.util.ErrorCodeUtil.*;

public interface BaseController {

    Logger LOG = Logger.getLogger(BaseController.class);

    default Result onlineErrorMsg(String msg, String res){
        Result<String> result = new Result<>();
        try {
            String status = JSONObject.fromObject(res).get("status") + "";
            String onlineMsg = onlineMsg(status);
            result.setModel(onlineMsg);
            if (onlineMsg.contains("成功"))
                result.setSuccess(true);
        } catch (Exception e) {
            result.setMsg(res);
        }
        LOG.info(msg + result);
        return result;
    }

    default Result dahanErrorMsg(String msg, String res){
        Result<String> result = new Result<>();
        try {
            String status = JSONObject.fromObject(res).get("result")+"";
            String dahanMsg = dahanMsg(status);
            result.setModel(dahanMsg);
            if (dahanMsg.contains("成功"))
                result.setSuccess(true);
        } catch (Exception e) {
            result.setMsg(res);
        }
        LOG.info(msg + result);
        return result;
    }

    default Result guoduErrorMsg(String msg, String res){
        Result<String> result = new Result<>();
        try {
            String status = readStringXml(res);
            String guoduMsg = guoduMsg(status);

            result.setModel(guoduMsg);
            if (guoduMsg.contains("成功"))
                result.setSuccess(true);
        } catch (Exception e){
            result.setMsg(res);
        }
        LOG.info(msg + result);
        return result;
    }

    default String readStringXml(String xml) {
        Document doc = null;
        try {
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            return rootElt.elementText("code");
        } catch (DocumentException e) {
            return xml;
        } catch (Exception e) {
            return xml;
        }
    }

}
